package com.py.framework.scheduler.job;

import java.util.List;

import org.quartz.CronExpression;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import com.py.framework.core.log.ExceptionLogger;
import com.py.framework.scheduler.common.JobConstants;
import com.py.framework.scheduler.entity.TaskEntity;
import com.py.framework.scheduler.job.detail.DefaultJobDetail;
import com.py.framework.scheduler.service.TaskService;

/**
 * 任务调度执行者
 * @author Leegern
 * @date   2018年5月7日
 */
public class JobScheduler {
	
	@Autowired
	private TaskService taskService;
	@Autowired
	private JobManager  jobManager;
	
	
	/**
	 * 初始化任务
	 */
	public void initJob() {
		// 获取所有任务数据
		List<TaskEntity> datas = taskService.getAllTasks();
		if (! CollectionUtils.isEmpty(datas)) {
			for (TaskEntity taskEntity : datas) {
				if (null != taskEntity) {
					// 设置任务
					this.setJobDetail(taskEntity);
				}
			}
			// 启动所有定时任务
			try {
				jobManager.startJobs();
			} catch (SchedulerException e) {
				ExceptionLogger.error(e);
			}
		}
	}
	
	/**
	 * 设置任务
	 * @param taskEntity 
	 */
	public void setJobDetail(TaskEntity taskEntity) {
		if (null != taskEntity && CronExpression.isValidExpression(taskEntity.getCronExp())) {
			try {
				Job job = this.populateEntity(taskEntity);
				// 删除
				if (JobConstants.NUM_TWO == taskEntity.getDelFlag()) {
					// 删除任务
					jobManager.deleteJob(job);
				}
				// 更新
				else if (JobConstants.NUM_TWO == taskEntity.getUpdFlag()) {
					// 更新表达式
					jobManager.updateJob(job);
				}
				// 开启
				else if (JobConstants.STATUS_RUN == taskEntity.getTaskStatus()) {
					// 添加任务
					jobManager.addJob(job);
				}
				// 停用
				else if (JobConstants.STATUS_STOP == taskEntity.getTaskStatus()) {
					// 暂停任务
					jobManager.pauseJob(job);
				}
			} catch (Exception e) {
				ExceptionLogger.error(e);
			}
		}
	}
	
	/**
	 * 组装任务实体
	 * @param entity
	 * @return
	 */
	private Job populateEntity(TaskEntity entity) {
		Job job = new Job();
		job.setJobId(String.valueOf(entity.getId()));
		job.setJobName(entity.getTaskName());
		job.setDescription(entity.getTaskDesc());
		job.setCreateTime(entity.getCreateTime());
		job.setUpdateTime(entity.getUpdateTime());
		job.setCronExpression(entity.getCronExp());
		job.setRequestUrl(entity.getSysAddr() + entity.getTaskUrl());
		job.setJobClassName(DefaultJobDetail.class.getName());
		job.setJobMethodName(JobConstants.DEFAULT_JOB_METHOD);
		return job;
	}
}